import axios from '@/api/config';
import XEUtils from "./index";
import {Method} from "axios";
import {openLoading} from "@/utils/elementUtils";
//调用接口
export function sendRequest(url: string, method: Method, data?: string | object) {
    openLoading()
    return axios({
        method,
        url: url,
        data
    })
}
//无loading调用接口
export function sendNoLoadingRequest(url: string, method: Method, data?: string | object) {
    return axios({
        method,
        url: url,
        data
    })
}
//上传文件接口
export function sendUploadRequest(url: string, method: Method, data: any) {
    let forms = new FormData()
    forms.append('file', data)
    openLoading()
    return axios({
        method,
        url: url,
        data: forms,
        headers: {"Content-Type": "multipart/form-data"},
    })
}

/**
 * 批量ajax操作
 * @param {function(json,function(response),function(error))} fun (必填，方法名) - 批量使用的ajax方法
 *
 * @param {array} data (必填，数组) - 需要批量的数据
 *
 * @param {function(json[],json[])} finishFun (必填，方法) - 所有请求全部完成才会调用
 * @param {json} finishFun.json.data 请求发送的值
 * @param {json} finishFun.json.object 请求返回的值
 *
 * @param {function(json)} [successFun] (选填，方法) - 每次成功都会调用
 * @param {json} successFun.json.data 请求发送的值
 * @param {json} successFun.json.object 请求返回的值
 *
 * @param {function(json)} [falseFun] (选填，方法) - 每次失败都会调用
 * @param {json} falseFun.json.data 请求发送的值
 * @param {json} falseFun.json.object 请求返回的值
 */
export function sendAll(fun: Function, data: any[], finishFun: Function, successFun?: Function, falseFun?: Function) {
    let sendAllSum = data.length
    let sendAllNum = 0
    let successArray: any[] = []
    let errorArray: any[] = []

    XEUtils.arrayEach(data, (item) => {
        let tempJson = {}
        fun(item).then((response: any) => {
            sendAllNum++;
            tempJson = {
                data: item,
                object: response
            }
            successArray.push(tempJson);
            if (XEUtils.isFunction(successFun))
                successFun(tempJson)
            if (sendAllNum === sendAllSum) {
                finishFun(successArray, errorArray);
            }
        }).catch((error: any) => {
            sendAllSum--;
            tempJson = {
                data: item,
                object: error
            }
            errorArray.push(tempJson);
            if (XEUtils.isFunction(falseFun))
                falseFun(tempJson)
            if (sendAllNum === sendAllSum) {// 接口报错
                finishFun(successArray, errorArray);
            } else if (sendAllNum > sendAllSum) {// 代码报错
                // layer.closeAll('loading');
                console.error(error);
            } else {
                /*layer.load(1, {
                    // shade: [0.4,'#f8f8f8'] //0.1透明度的白色背景
                    shade: [0.4, '#999']
                });*/
            }
        })
    })
}